# encoding:utf-8
import requests
import json
import base64
import os

'''
人像动漫化
'''

# client_id 为官网获取的AK， client_secret 为官网获取的SK
AK = 'lgwuSbbujaNlAtn6Gng9kqsc'
SK = 'Ifu9zChVYjZZZczvFZpgGo0rb7D85kgw'
null = ''


def get_token():
    url = 'https://aip.baidubce.com/oauth/2.0/token'
    data = {}
    data['grant_type'] = 'client_credentials'
    data['client_id'] = AK
    data['client_secret'] = SK
    response = requests.post(url, data)
    content = response.content.decode('utf-8')
    content = json.loads(content)
    print('access_token:\t', content['access_token'])
    return content['access_token']

def base666(image):
    f1 = open(image, 'rb')
    f1_64 = base64.b64encode(f1.read())
    f1.close()
    f1_64 = f1_64.decode()
    return f1_64

def anime(face1, image):
    global null
    url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime' + \
          "?access_token=" + get_token()
    data = {"image": base666(face1)}
    print(data)
    headers = {'content-type': 'application/json'}
    # headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(url, data, headers=headers)
    # print(response.content)
    req_con1 = response.content.decode('utf-8')
    content = eval(req_con1)
    # print(content)
    result = content['image']
    imgdata = base64.b64decode(result)
    with open(image, 'wb') as fp:
        fp.write(imgdata)
        fp.close()

if __name__ == '__main__':
    image1 = './face_m.jpg'
    image = './face_m_anime.jpg'
    anime(image1, image)
